package tron.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import tron.entity.MyDoc;

/**
 * 全文检索初始化程序，检测索引是否存在，如果没存在就创建索引
 */
@Configuration
public class ApplicationInit implements ApplicationRunner {

    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            log.info("elasticSearch start init ...");
            IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(MyDoc.class);
            boolean exists = indexOperations.exists();
            if (!exists) {
                indexOperations.create();
                indexOperations.putMapping(indexOperations.createMapping(MyDoc.class));
            }
            log.info("index is exists elasticSearch init end");
        } catch (Exception e) {
        }
    }
}
